package pro.shuangxi.model.book.helper.book;

import mybatisplus.pojo.Book;
import mybatisplus.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import pro.shuangxi.model.book.pojo.Story;

import java.util.*;
import java.util.function.BiConsumer;

/**
 * @author ：mengshx
 * @date ：Created in 2020/12/27 14:56
 * @description：
 */
public class BookRepository {
    @Autowired
    private IBookService bookService;
    private Map<Integer, Story> center = new HashMap<>();
    public  BookRepository(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                center.forEach(new BiConsumer<Integer, Story>() {
                    @Override
                    public void accept(Integer integer, Story story) {
                        Date time = story.getTime();
                        Date now = new Date();
                        if(now.getTime() - time.getTime()>1000*60*60*24){
                            center.remove(integer);
                        }

                    }
                });

            }
        },0,1000*60*60*24);
    }
    public Story getOneById(Integer bookid){
        Story story = center.get(bookid);
        if (story == null) {
            Book book = bookService.getById(bookid);
            story = new Story(book.getPath());
        }

        return story;
    }
}
